use rand::*;
use std::io::*;
use std::str::FromStr;

fn main(){
    //gen random number
    let mut rng = rand::thread_rng();
    let randnum = rng.next_u32() % 1000;

    //game start
    printstr("We had a serect number,guess it.\n");

    //when succ,push any thing will exit
    let mut succ = false;
    loop {
        if !succ {
            printstr("Type your number:\n");
        } else {
            printstr("input anything to exit.\n");
            let mut guess = String::new();
            stdin().read_line(&mut guess).expect("error input");
            return;
        }
        //read a line
        let result = inputnum();
        let resultnum: u32;
        match result {
            Ok(num) => {
                resultnum = num;
            }
            Err(_) => continue,
        }

        //上面是清晰的判断写法，当然也可用下面这两种写法
        // rust 精简写法，直接返回值
        // let resultnum:u32 = match inputnum();
        // {
        //     Ok(num)=>num,
        //     Err(_)=>continue,
        // };

        // 全展开写法，不用match而是 if else
        // let r2=inputnum();
        // let mut resultnum: u32 = 0;
        // if r2.is_ok()
        // {
        //     resultnum = r2.unwrap();
        // }
        // else if r2.is_err()
        // {
        //     continue;
        // }

        println!("your num is:{}", resultnum);

        if resultnum < randnum {
            printstr("your num is too small\n");
        } else if resultnum > randnum {
            printstr("your num is too big\n");
        } else {
            printstr("succ you got it\n");
            succ = true;
        }
    }
}
fn inputnum() -> std::result::Result<u32, String> {
    let mut guess = String::new();
    stdin().read_line(&mut guess).expect("error input");
    let result = u32::from_str(guess.trim());
    match result {
        Ok(num) => {
            return Ok(num);
        }
        Err(_) => {
            return Err(String::from("error number"));
        }
    }
}
fn printstr(mut _str: &str) {
    stdout().write(_str.as_bytes()).expect("error");
}
